<script setup>
import { ref, watch } from 'vue'

const question = ref('')
const imageSrc = ref('')
const answer = ref('问题通常需要一个问号. ;-)')
const loading = ref(false)

// 可以直接侦听一个 ref
watch(question, async (newQuestion, oldQuestion) => {       //async异步
  if (newQuestion.includes('?')) {          //includes()函数用于判断字符串中是否包含某个字符串
    loading.value = true
    answer.value = 'Thinking...'
    try {       //await用于等待一个异步任务执行完成的结果,Fetch返回Promise,定义变量res接收
      const res = await fetch('https://yesno.wtf/api')   
      const data = await res.json();    //data接收Promise中的json文件
      answer.value = data.answer
      imageSrc.value = data.image
    } catch (error) {
      answer.value = '错误,找不到. ' + error
    } finally {
      loading.value = false
    }
  }
})
</script>

<template>
  <p>
    问我一个 yes或no 的问题:
    <input v-model="question" :disabled="loading" />
  </p>
  <p>{{ answer }}</p>
  <img :src="imageSrc" />
</template>